package com.net.device;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.net.RetrofitUtils;
import com.net.device.entity.PostOrderEntity;
import com.net.device.entity.ResponseEntity;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * create by cjx on 2024/7/15
 * desc:
 */
public class DeviceApiRepository {
    private static DeviceApiRepository repository;
    private DeviceApi api;

    public static DeviceApiRepository getInstance() {
        if (repository == null) {
            synchronized (DeviceApiRepository.class) {
                if (repository == null) {
                    repository = new DeviceApiRepository();
                }
            }
        }
        return repository;
    }

    private DeviceApiRepository() {
    }

    public DeviceApiRepository init(String url) {
        if(url == null){
            this.api = null;
            return this;
        }
        this.api = RetrofitUtils.getInstance().create(url, DeviceApi.class);
        return this;
    }


    // 推送订单到设备
    public Disposable postOrder(PostOrderEntity order,
                                Consumer<ResponseEntity> onNext,
                                Consumer<Throwable> onError) {
        if (api == null) {
            return null;
        }
        String body = new Gson().toJson(order);
        Observable<ResponseBody> observable = api.postOrder(getRequestBody(body));
        return observable.subscribeOn(Schedulers.io())
                .map(this::parserBody)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(onNext, onError);
    }

    private RequestBody getRequestBody(String body) {
        return RequestBody.create(MediaType.parse("Content-Type:application/json"), body);
    }

    /**
     * 内部服务器通用转换工具， 如果你的项目用的不是这套模型，自己差异包里面搞
     */
    private ResponseEntity parserBody(ResponseBody responseBody) {
        ResponseEntity rb = null;
        try {
            if (responseBody != null) {
                String body = responseBody.string();
                if (body.isEmpty()) {
                    return null;
                }
                rb = new Gson().fromJson(body, new TypeToken<ResponseEntity>() {
                }.getType());
            }
        } catch (IOException ignore) {
        }
        return rb;
    }
}
